package com.zsxj.xixi.common;

import com.google.common.base.Objects;
import com.zsxj.xixi.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @author caoruiqi
 * @创建时间 2020/10/26
 * @描述
 */
@Slf4j
public class AuthContext {

    /**
     * 用户id
     */
    public static final String CURRENT_USER_ID = "userId";
    /**
     * 用户商户号id
     */
    public static final String CURRENT_USER_MERCHANT_ID = "merchantId";
    /**
     * 用户名称
     */
    public static final String CURRENT_USER_NAME = "userName";
    /**
     * 用户类型 @1 销售商 @2供应商 @3员工
     */
    public static final String CURRENT_USER_TYPE = "userType";
    /**
     * 分销 - 分销商的 nick_no
     */
    public static final String DISTRIBUTE_SELLER_NICK_NO = "nickNo";
    /**
     * 分销模式类型
     */
    public static final String FENXIAO_MODEL_TYPE = "fenxiaoModelType";
    public static final String MODEL_TYPE_SELF_SALE = "SELF_SALE";
    public static final String MODEL_TYPE_FENXIAO_SALE = "FENXIAO_SALE";
    /**
     * 代拿端id
     */
    public static final String CURRENT_FORWARDER_ID = "forwarderId";
    /**
     * 代拿回调的forwarderId
     */
    public static final String CURRENT_SELLER_ID = "sellerId";

    public static final byte TYPE_SELLER = 1;
    public static final byte TYPE_SUPPLIER = 2;


    private static String getRequestParameter(String parameterName) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String value = request.getParameter(parameterName);
            //修复null字符串的bug 生产环境的bug  如果用户名称 为null字符串会有bug
            String nullStr = "null";
            if (nullStr.equals(value) || org.springframework.util.StringUtils.isEmpty(value)) {
                return null;
            }
            return value;
        }
        return null;
    }

    public static String getActive() throws IOException {
        String active = "test";
        //先获取主yaml中的active值
        Yaml applicationYaml = new Yaml();
        Resource actResource = new ClassPathResource("application.yml");
        if (actResource != null) {
            Map map = (Map) applicationYaml.load(actResource.getInputStream());
            active = ((Map) (((Map) map.get("spring")).get("profiles"))).get("active").toString();
        }
        return active;
    }

    public static boolean isDistribute() {
        return Objects.equal(getFenxiaoModelType(), MODEL_TYPE_FENXIAO_SALE);
    }

    public static boolean isForwarder() {
        return !Objects.equal(getForwarderId(), null);
    }

    public static String getFenxiaoModelType() {
        return getRequestParameter(FENXIAO_MODEL_TYPE);
    }

    public static Long getUserId() {
        String userId = getRequestParameter(AuthContext.CURRENT_USER_ID);
        return userId == null ? 0L : Long.parseLong(userId);
    }

    public static Long getMerchantId() {
        String merchantId = getRequestParameter(AuthContext.CURRENT_USER_MERCHANT_ID);
        return merchantId == null ? null : Long.parseLong(merchantId);
    }

    public static Long getForwarderId() {
        String forwarderId = getRequestParameter(AuthContext.CURRENT_FORWARDER_ID);
        return forwarderId == null ? null : Long.parseLong(forwarderId);
    }

    public static Long getSellerId() {
        String sellerId = getRequestParameter(AuthContext.CURRENT_SELLER_ID);
        return StringUtils.isEmpty(sellerId) ? null : Long.parseLong(sellerId);
    }

    /**
     * 分销商 nick_no
     *
     * @author zhengbaole
     * @lastEditor zhengbaole
     * @createTime 2021/3/15 1:15 PM
     * @editTime 2021/3/15 1:15 PM
     */
    public static String nickNo() {
        return getRequestParameter(AuthContext.DISTRIBUTE_SELLER_NICK_NO);
    }

    public static String getUserName() {
        String userName = getRequestParameter(AuthContext.CURRENT_USER_NAME);
        if (userName == null) {
            return "系统操作";
        }
        try {
            userName = URLDecoder.decode(userName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("get userName throw Exception ", e);
        }
        log.info("get request userName -> {}", userName);
        //        userName = "9636";
        return StringUtils.isEmpty(userName) ? "系统操作" : userName;
    }

    public static Byte getUserType() {
        String value = getRequestParameter(CURRENT_USER_TYPE);
        if (value == null) {
            return null;
        }

        try {
            return Byte.parseByte(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 获取 AuthContext 对应的对象
     *
     * @return AuthContext 对应的对象
     * @author zhengbaole
     * @lastEditor zhengbaole
     * @createTime 2020/12/22 3:05 下午
     * @editTime 2020/12/22 3:05 下午
     **/
    public static AuthObject getAuthObject() {
        return new AuthObject(getMerchantId(), getUserId());
    }

    @Data
    @AllArgsConstructor
    public static class AuthObject {

        private Long merchantId;

        private Long userId;
    }
}
